<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Ajax extends CI_Controller {
    /*
     actions:
     * 1 - showGames(IDLeague)
     */
    public function __construct()
    {
        parent::__construct();
        $this->load->model('game');
    }
    
    // index function
    public function index(){
       $action = $_POST['action'];
       switch ($action){
           case 1: {
               $IDLeague = $_POST['IDLeague'];
               $this->showGames($IDLeague);
               break;
           }
           case 2: {
               $IDCountry = $_POST['IDCountry'];
               $this->showLeagues($IDCountry);
               break;
           }
           default : break;
       }
    }
    public function showGames($IDLeague){
        $games = $this->game->getAllActiveGamesByIDLeague($IDLeague);
        $league = $this->game->getLeagueByID($IDLeague);
        $gamesAsArrays = array();
        foreach($games as $game){
            array_push($gamesAsArrays, $game->toArray());
        }
        $json = array('games' => $gamesAsArrays, 'league' => $league->getFullName());
        echo json_encode($json);
    }
    public function showLeagues($IDCountry){
        $leagues = $this->game->getAllLeaguesWithPredictionsByIDCountry($IDCountry);
        $leaguesAsArrays = array();
        $increment = 0;
        foreach($leagues as $league){
            $gamesAsArrays = array();
            foreach($league->getGameList() as $game){
                array_push($gamesAsArrays, $game->toArray());
            }
            $leagueAsArray = $league->toArray();
            $leagueAsArray['games']=$gamesAsArrays;
            array_push($leaguesAsArrays, $leagueAsArray);
            $increment++;
        }
        //print_r($leaguesAsArrays);
        $key = 'leagues';
        $value = $leaguesAsArrays;
        $json = array($key => $value);
        echo json_encode($json);
    }
}